#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <cmath>
#include<vector>
using namespace std;
struct detail {
    string pre;
    int key;
    string next;
};
int main()
{
    string head;
    unordered_map<string, int> hashpk;
    unordered_map<string, string> hashpn;
    unordered_map<string, int > kk;
    unordered_map<int, int> q;
    vector<detail> del;
    int cnt;
    cin >> head >> cnt;

    for (int i = 0; i < cnt; i++)
    {
        string p, n;
        int k;
        cin >> p >> k >> n;
        hashpk[p] = k;
        hashpn[p] = n;
    }
    string p = head;
    bool flg = false;
    while (p != "-1")
    {
        q[abs(hashpk[p])]++;
        string np = hashpn[p];
        if(q.count(abs(hashpk[np])) && q[abs(hashpk[np])] > 0)
        {
            string k = np;

            del.push_back({ np,hashpk[np],hashpn[np] });
            hashpn[p] = hashpn[np];
            hashpk.erase(k);
            hashpn.erase(k);

            continue;
        }
        cout << p << ' ' << hashpk[p] << ' ' << hashpn[p] << endl;
        string k = p;
        p = hashpn[p];
        hashpk.erase(k);
        hashpn.erase(k);
    }

    for (int i = 0; i < del.size(); i++)
    {
        if (i + 1 < del.size())
        {
            del[i].next = del[i + 1].pre;
        }
        else {
            del[i].next = "-1";
        }
        cout << del[i].pre << ' ' << del[i].key << ' ' << del[i].next << endl;
    }

    return 0;
}